package com.example.sqlliteapp;
import android.content.Context;
import android.util.Base64;
import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
public class XunfeiChatService {
    private final Context context;
    private final OkHttpClient client;
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static final String APP_ID = "YOUR_APP_ID";
    public XunfeiChatService(Context context) {
        this.context = context.getApplicationContext();
        this.client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
    }
    public void sendMessage(String query, final ChatCallback callback) {
        try {
            String baseUrl = context.getString(R.string.xunfei_base_url);
            String apiKey = context.getString(R.string.xunfei_api_key);
            JSONObject requestBody = new JSONObject();
            JSONObject header = new JSONObject();
            header.put("app_id", APP_ID);
            JSONObject parameter = new JSONObject();
            JSONObject chat = new JSONObject();
            chat.put("domain", "general");
            chat.put("temperature", 0.5);
            chat.put("max_tokens", 2048);
            parameter.put("chat", chat);
            JSONObject payload = new JSONObject();
            JSONObject message = new JSONObject();
            JSONObject[] text = new JSONObject[1];
            text[0] = new JSONObject();
            text[0].put("role", "user");
            text[0].put("content", query);
            message.put("text", text);
            payload.put("message", message);
            requestBody.put("header", header);
            requestBody.put("parameter", parameter);
            requestBody.put("payload", payload);
            Request request = new Request.Builder()
                    .url(baseUrl)
                    .post(RequestBody.create(requestBody.toString(), JSON))
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .addHeader("X-App-Id", APP_ID)
                    .addHeader("X-Request-Date", getCurrentTimeGMT())
                    .addHeader("Authorization", generateAuthHeader(apiKey, requestBody.toString()))
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    callback.onFailure("网络错误: " + e.getMessage());
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try (ResponseBody body = response.body()) {
                        if (!response.isSuccessful()) {
                            callback.onFailure("API错误: " + response.code() + " - " + body.string());
                            return;
                        }
                        callback.onSuccess(body.string());
                    }
                }
            });
        } catch (JSONException e) {
            callback.onFailure("请求构造失败: " + e.getMessage());
        }
    }
    private String generateAuthHeader(String apiKey, String requestBody) {
        try {
            String timestamp = getCurrentTimeGMT();
            String signatureOrigin = String.format("host: %s\ndate: %s\nPOST /v2.1/chat HTTP/1.1",
                    "spark-api.xf-yun.com", timestamp);
            String signatureSha = hmacSHA256(signatureOrigin, apiKey);
            String signature = Base64.encodeToString(signatureSha.getBytes(), Base64.NO_WRAP);
            String authorization = String.format(
                    "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"",
                    apiKey, "hmac-sha256", "host date request-line", signature);
            return authorization;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    private String hmacSHA256(String data, String key) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update((data + key).getBytes());
        byte[] digest = md.digest();
        return bytesToHex(digest);
    }
    private String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
    private String getCurrentTimeGMT() {
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        return sdf.format(new Date());
    }
    public interface ChatCallback {
        void onSuccess(String response);
        void onFailure(String error);
    }
}